package app.service.impl;

import app.domain.Role;
import app.service.ServiceUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.LinkedHashSet;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements org.springframework.security.core.userdetails.UserDetailsService {
    @Autowired
    private ServiceUser serviceUser;
    @Autowired
    private app.domain.User user;
    /**
     * 通过用户名来加载用户  - 用户的角色、权限等信息。这个方法主要用于从系统数据中查询并加载具体的用户到Spring Security中。
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserDetails userDetails;
        //查询数据库
        app.domain.User query = serviceUser.query(s);
        if (query == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }else {
            Set<Role> roles = new LinkedHashSet<>();
            for (Role role : query.getRoles()) {
                roles.add(role);
                user.setRoles(roles);
            }
            System.out.println(query.getRoles());
            userDetails = new User(s, query.getPassword(), user.getAuthorities());
        }
        return userDetails;
    }
}
